import { ExpressErrorMiddlewareInterface, Middleware, NotFoundError } from 'routing-controllers';
import { Service } from 'typedi';
import { logger } from '@vendor/logger';
import sendMessage from '@vendor/dingTalk';

@Middleware({ type: 'after' })
@Service()
export class HttpErrorMiddleware implements ExpressErrorMiddlewareInterface {
    error(error: any, request: any, response: any, next: (err?: any) => any): void {
        if (error instanceof NotFoundError) {
            response.location('/');
        } else if (error) {
            const { method, originalUrl } = request;
        
            let params = '';
            switch (method.toUpperCase()) {
                case 'POST':
                    params = JSON.stringify(request.body);
                    break;
                case 'PUT':
                    params = JSON.stringify(request.body);
                    break;
                case 'GET':
                    params = JSON.stringify(request.query);
                    break;
                case 'DELETE':
                    params = JSON.stringify(request.query);
                    break;
                default:
            }
        
            const errorMessage = `${originalUrl} : params ${params}\n${error.message}\n${error.stack}`;
            logger.error(errorMessage);

            sendMessage('模版渲染错误', errorMessage);

            response.status(500).send(process.env.NODE_ENV === 'development' ? errorMessage : 'server error');
        } else {
            next(error);
        }
    }
}